<template>
  <div style="padding-top:20px">
    <!-- 显示sn -->
    <div class="sn">
      <div class="sn_content">
        <span>sn :</span>
        <el-input v-model="sn" style="max-width:218px;margin-left:20px"></el-input>
        <div style="width:80px;height:80px">
          <img :src="imgUrl" alt style="width:100%;height:100%" />
        </div>

        <el-button
          type="primary"
          style="height:40px;position:relative;top:50%;transform:translateY(-50%);margin-left:2px"
          @click="changeSn"
        >修改</el-button>
        <el-button
          type="primary"
          style="height:40px;position:relative;top:50%;transform:translateY(-50%);margin-left:10px"
          @click="changeSnCopy(sn)"
        >复制</el-button>
      </div>
      <div class="sn_content_ji">
        <span>机器码 :</span>
        <div style="width:290px;margin-left:20px;text-align:left;">{{mechanicalCode}}</div>
        <el-button
          type="primary"
          style="height:40px;position:relative;top:50%;transform:translateY(-50%);margin-left:10px"
          @click="copy(mechanicalCode)"
        >复制</el-button>
      </div>
      <div class="sn_content_ji" v-if="license_status=='0'">
        <span>授权码 :</span>
        <el-input v-model="authorizationCode" style="max-width:290px;margin-left:20px"></el-input>
        <el-button
          type="primary"
          style="height:40px;position:relative;top:50%;transform:translateY(-50%);margin-left:10px"
          @click="handleActivation"
        >激活</el-button>
      </div>
      <div class="sn_content_ji" v-if="license_status=='1'">
        <span>授权码 :</span>
        <div style="width:290px;margin-left:20px;text-align:left;">{{authorizationCode}}</div>
        <el-button
          type="text"
          style="height:40px;position:relative;top:50%;transform:translateY(-50%);margin-left:10px;color:black;font-size:18px"
        >已激活</el-button>
      </div>
    </div>
    <div style="width:25%;min-width:500px;padding-left:50px;box-sizing:border-box">
      <el-divider></el-divider>
    </div>

    <!-- 显示文件上传 -->
    <el-form ref="fileForm" :model="form" label-width="150px" label-suffix="：" class="fileForm">
      <el-form-item label="选择文件" class="uploadfile">
        <div class="upload-file-box">
          <el-upload
            ref="upload"
            action="#"
            :http-request="uploadFile"
            :show-file-list="showFileList"
            :on-remove="handleRemove"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <el-input
              v-model="fileName"
              placeholder="点击浏览本地文件..."
              autocomplete="off"
              clearable
              @clear="handleRemove"
              style="width:290px"
            />
          </el-upload>
          <div class="upload-btn-box" style="margin-left:10px">
            <el-button type="primary" class="upload-btn" @click="upload">上传</el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script type="text/javascript">
export default {
  data() {
    return {
      form: {},
      showFileList: false,
      fileName: '',
      uploadfile: {},
      sn: '',
      imgUrl: '',
      mechanicalCode: '', //机器码
      authorizationCode: '', //授权码
      license_status: ''
    }
  },

  methods: {
    uploadFile(f) {
      if (f !== undefined) {
        this.uploadfile = f
        this.fileName = f.file.name
      }
    },
    handleRemove() {
      this.$refs.upload.clearFiles()
      this.uploadfile = ''
      this.filePercentage = 0
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    async upload() {
      // 上传
      var that = this
      if (Object.keys(this.uploadfile).length > 0) {
        var params = {
          token: window.sessionStorage.getItem('token'),
          file_type: 0
        }
        var hostname = window.location.host
        var url =
          'http://' +
          hostname +
          '/baio/file_upload' +
          '?' +
          'token=' +
          window.sessionStorage.getItem('token') +
          '&file_type=9'
        var request = new XMLHttpRequest()
        var fd = new FormData()
        fd.append('file', this.uploadfile.file)
        //监听事件
        // request.upload.addEventListener('progress', uploadProgress, false)
        request.upload.onprogress = function(evt) {
          that.filePercentage = Math.round((evt.loaded / evt.total) * 100)
        }
        request.onload = function(res) {
          if (JSON.parse(res.currentTarget.response).code == '1000') {
            that.$message.success('上传成功')
            that.$refs.upload.clearFiles()
            that.uploadfile = ''
            that.fileName = ''
          } else {
            that.$message.success('上传失败')
            that.$refs.upload.clearFiles()
            that.uploadfile = ''
            that.fileName = ''
          }
        }
        request.upload.onloadstart = function() {
          //   that.updateDisabled = true
          //   that.filePercentageShow = true
        }

        //发送文件和表单自定义参数
        request.open('POST', url, true)
        request.send(fd)
      } else {
        this.$message.warning('文件不能为空')
      }
    },
    async getSn() {
      var data = new Date()
      var month =
        data.getMonth() < 9 ? '0' + (data.getMonth() + 1) : data.getMonth() + 1
      var date = data.getDate() <= 9 ? '0' + data.getDate() : data.getDate()
      var tt =
        data.getFullYear() +
        '' +
        month +
        date +
        data.getHours() +
        data.getMinutes() +
        data.getSeconds()
      const { data: res } = await this.$http.post(
        'sn',
        {
          time: tt
        },
        {
          params: {
            token: window.sessionStorage.getItem('token')
          }
        }
      )
      if (res.code !== '1000') {
        this.$message.error('sn获取失败')
      } else {
        this.sn = res.data.sn
        this.getImgUrl()
      }
    },
    // 修改
    async changeSn() {
      var data = new Date()
      var month =
        data.getMonth() < 9 ? '0' + (data.getMonth() + 1) : data.getMonth() + 1
      var date = data.getDate() <= 9 ? '0' + data.getDate() : data.getDate()
      var tt =
        data.getFullYear() +
        '' +
        month +
        date +
        data.getHours() +
        data.getMinutes() +
        data.getSeconds()
      const { data: res } = await this.$http.post(
        'sn',
        {
          time: tt,
          sn: this.sn
        },
        {
          params: {
            token: window.sessionStorage.getItem('token')
          }
        }
      )
      if (res.code == '1000') {
        this.$message.success('sn修改成功')
        this.getImgUrl()
      } else {
        this.$message.error('sn修改失败')
      }
    },
    // 复制
    changeSnCopy(row) {
      console.log('复制')

      let url = row
      let oInput = document.createElement('input')
      oInput.value = url
      document.body.appendChild(oInput)
      oInput.select() // 选择对象;

      document.execCommand('Copy') // 执行浏览器复制命令
      this.$message({
        message: '复制成功',
        type: 'success'
      })
      oInput.remove()
    },
    // 获取图片地址
    getImgUrl() {
      this.imgUrl =
        'http://' +
        window.location.hostname +
        '/qrcode.png' +
        '?' +
        new Date().getTime()
      // this.imgUrl = 'http://'+'192.168.1.211'+'/qrcode.png'+'?'+new Date().getTime()
    },
    // 获取机器码
    async getInfo() {
      const { data: res } = await this.$http.get(
        'license',

        {
          params: {
            token: window.sessionStorage.getItem('token')
          }
        }
      )
      if (res.code !== '1000') {
        this.$message.error('获取失败')
      } else {
        this.mechanicalCode = res.data.license_id
        this.authorizationCode = res.data.license
        this.license_status = res.data.license_status
      }
    },
    // 复制
    copy(row) {
      let url = row
      let oInput = document.createElement('input')
      oInput.value = url
      document.body.appendChild(oInput)
      oInput.select() // 选择对象;

      document.execCommand('Copy') // 执行浏览器复制命令
      this.$message({
        message: '复制成功',
        type: 'success'
      })
      oInput.remove()
    },
    // 激活
    async handleActivation() {
      const { data: res } = await this.$http.post(
        'license',
        { license: this.authorizationCode },
        {
          params: {
            token: window.sessionStorage.getItem('token')
          }
        }
      )
      if (res.code !== '1000') {
        this.$message.error(res.data.info)
        this.getInfo()
      } else {
        this.$message.success('激活成功')
        // this.authorizationCode = res.data.license
        this.getInfo()
      }
    }
  },
  mounted() {
    this.getSn()
    this.getInfo()
  }
}
</script>

<style lang="less" scoped>
.upload-file-box {
  display: flex;
  align-items: center;
}
.uploadfile,
.sn {
  // width: 25%;
  min-width: 500px;
  // margin-top: 20px;
}
.sn_content {
  // display: inline-block;
  display: flex;
  // width: 138px;
  text-align: right;
  padding-left: 100px;
  color: #606266;
  height: 80px;
  line-height: 80px;
  // box-sizing: border-box;
}
.sn_content_ji {
  display: flex;
  // width: 138px;
  text-align: right;
  padding-left: 69px;
  color: #606266;
  height: 80px;
  line-height: 80px;
}
</style>